package com.openvas.core.gas.rest;

import com.coconet.gas.biz.IpsRuleBiz;
import com.coconet.gas.biz.ReportBiz;
import com.coconet.gas.biz.TargetIpBiz;
import com.coconet.gas.biz.TaskIpBiz;
import com.coconet.gas.constant.dwEnum;
import com.coconet.gas.domain.TaskInfo;
import com.coconet.gas.domain.TaskView;
import com.coconet.gas.service.TaskService;
import com.coconet.gas.service.impl.OpenvasTool2;
import com.coconet.gas.vo.dw.Report;
import com.coconet.gas.vo.dw.TaskIp;
import com.coconet.gas.vo.dw.st.CommonFy;
import com.coconet.gas.vo.request.IpPort;
import com.coconet.gas.vo.request.PortListVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxa.entity.ConfigEntity;
import com.gxa.entity.TargetEntity;
import com.gxa.entity.TaskEntity;
import com.gxa.entity.TaskInfoEntity;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import response.BaseResponse;
import response.ObjectRestResponse;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController

public class TaskRest {

    @Resource
    private IpsRuleBiz ipsRuleBiz;
    @Resource
    private TargetIpBiz targetIpBiz;
    @Resource
    private TaskIpBiz taskIpBiz;
    @Resource
    private TaskService taskService;
    @Resource
    private OpenvasTool2 openvasTool;
    @Resource
    private ReportBiz reportBiz;

    //private OpenvasTool2 openvasTool = new OpenvasTool2();



    /**
     * 新建端口集合
     * @param portListVo
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "新建端口集合", httpMethod = "POST")
    @PostMapping(value = "/createPortList")
    public BaseResponse createPortList(@RequestBody PortListVo portListVo) throws Exception {
        taskService.createPortList(portListVo);
        return new BaseResponse(dwEnum.SUCCEESS.code(), "新建端口集合成功");
    }


    /**
     * 获取端口集合
     * @param cfy
     * @return
     */
    @ApiOperation(value = "获取端口集合列表", httpMethod = "POST")
    @PostMapping(value = "/getPortList")
    public ObjectRestResponse getPortList(@RequestBody CommonFy cfy) {

        List<Map<String, Object>> portList = new ArrayList<>();
        try {
            portList = openvasTool.getPortList();
            List<TargetEntity> targetList = openvasTool.getTargetList();
            for (Map<String, Object> portMap : portList) {
                for (TargetEntity target : targetList) {
                    if (portMap.get("portId").equals(target.getPortId())) {
                        portMap.put("inUse", 1);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        PageHelper.startPage(cfy.getCurrentPage(), cfy.getPageSize());
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(portList);
        return new ObjectRestResponse(dwEnum.SUCCEESS.code(), "", pageInfo);
    }


    /**
     * 批量删除端口
     * @param portIdList
     * @return
     * @throws Exception
     */

    @ApiOperation(value = "批量删除端口集合", httpMethod = "DELETE")
    @DeleteMapping(value = "/deletePortList")
    public BaseResponse deletePortList(@RequestBody List<String> portIdList) throws Exception {
        for (String portId : portIdList) {
            openvasTool.deletePortList(portId);
        }
        return new BaseResponse(dwEnum.SUCCEESS.code(), "删除端口集合成功");
    }


    @ApiOperation(value = "新建target", httpMethod = "POST")
    @PostMapping(value = "/createTarget")
    public BaseResponse createTarget(@RequestBody TargetEntity target) throws Exception {
        taskService.createTarget(target);
        return new BaseResponse(dwEnum.SUCCEESS.code(), "新建扫描目标成功");
    }

    @ApiOperation(value = "获取Target列表", httpMethod = "POST")
    @PostMapping(value = "/getTargetList")
    public ObjectRestResponse getTargetList(@RequestBody CommonFy cfy) {
        List<TargetEntity> targetList = new ArrayList<>();
        try {
            targetList = openvasTool.getTargetList();
            List<TaskInfoEntity> taskList = openvasTool.getTasksList();
            for (TargetEntity target : targetList) {
                for (TaskInfoEntity task : taskList) {
                    if (task.getTargetId().equals(target.getUuid())) {
                        target.setInUse(1);
                    }
                }
                List<Map<String, Object>> portList = openvasTool.getPortList();
                for (Map<String, Object> port : portList) {
                    if (target.getPortId().equals(port.get("portId"))) {
                        target.setPortName(port.get("name").toString());
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        PageHelper.startPage(cfy.getCurrentPage(), cfy.getPageSize());
        PageInfo<TargetEntity> pageInfo = new PageInfo<TargetEntity>(targetList);
        return new ObjectRestResponse(dwEnum.SUCCEESS.code(), "", pageInfo);
    }

    @ApiOperation(value = "批量删除target", httpMethod = "DELETE")
    @DeleteMapping(value = "/deleteTarget")
    public BaseResponse deleteTarget(@RequestBody List<String> targetIdList) throws Exception {
        for (String targetId : targetIdList) {
            openvasTool.deleteTarget(targetId);
        }
        return new BaseResponse(dwEnum.SUCCEESS.code(), "删除扫描目标成功");
    }


    @ApiOperation(value = "新建任务", httpMethod = "POST")
    @PostMapping(value = "/createTask")
    public BaseResponse createTask(@RequestBody TaskEntity taskEntity) throws Exception {
        taskService.createTask(taskEntity);
        return new BaseResponse(dwEnum.SUCCEESS.code(), "新建任务成功");
    }


    /**
     * 获取扫描列表
     * @param cfy
     * @return
     */
    @ApiOperation(value = "获取Task列表", httpMethod = "POST")
    @PostMapping(value = "/getTasksList")
    public ObjectRestResponse getTasksList(@RequestBody CommonFy cfy) {
        List<TaskView> taskList = new ArrayList<>();
        try {
            taskList = openvasTool.getTasksListNew();
            System.out.println(taskList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (TaskView task : taskList) {
            String checkTime = task.getModificationTime();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date parse = sdf.parse(checkTime);
                Calendar rightNow = Calendar.getInstance();
                rightNow.setTime(parse);
                rightNow.add(Calendar.HOUR_OF_DAY, 16);
                String format = sdf.format(rightNow.getTime());
                task.setModificationTime(format);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

//        Collections.sort(taskList, (t1, t2) -> t2.getModificationTime().compareTo(t1.getModificationTime()));
//        PageHelper.startPage(cfy.getCurrentPage(), cfy.getPageSize());
//        PageInfo<TaskView> pageInfo = new PageInfo<TaskView>(taskList);
//                task.setCheckTime(format);
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//
//        }
        Collections.sort(taskList, (t1, t2) -> t2.getModificationTime().compareTo(t1.getModificationTime()));
        PageHelper.startPage(cfy.getCurrentPage(), cfy.getPageSize());
        PageInfo<TaskView> pageInfo = new PageInfo<TaskView>(taskList);
        return new ObjectRestResponse(dwEnum.SUCCEESS.code(), "", pageInfo);
    }

    @ApiOperation(value = "获取task的详细属性，和openvas网页版一样",httpMethod = "GET")
    @GetMapping("/findTaskByTaskId")
    public ObjectRestResponse findOneTaskByTaskId(String taskId){
        TaskInfo oneTask=null;
        try {
             oneTask= openvasTool.getOneTask(taskId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ObjectRestResponse(dwEnum.SUCCEESS.code(),"",oneTask);
    }

    @ApiOperation(value = "批量删除任务", httpMethod = "DELETE")
    @DeleteMapping(value = "/deleteTask")
    public BaseResponse deleteTask(@RequestParam List<String> taskIdList) {
        for (String taskId : taskIdList) {
            taskService.deleteTask(taskId);
        }
        return new BaseResponse(dwEnum.SUCCEESS.code(), "删除任务成功");
    }

    @ApiOperation(value = "获取Config列表", httpMethod = "GET")
    @GetMapping(value = "/getConfigList")
    public ObjectRestResponse getConfigList() {
        List<ConfigEntity> configList = new ArrayList<>();
        try {
            configList = openvasTool.getConfigList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ObjectRestResponse(dwEnum.SUCCEESS.code(), "", configList);
    }


    @ApiOperation(value = "开始任务", httpMethod = "GET")
    @GetMapping(value = "/startTask/{taskId}")
    public ObjectRestResponse startTask(@PathVariable String taskId) {
        taskService.startTask(taskId);
        return new ObjectRestResponse(dwEnum.SUCCEESS.code(), "", "开启扫描任务成功");
    }


    @ApiOperation(value = "获取报告结果", httpMethod = "GET")
    @GetMapping(value = "/getReport/{reportId}")
    public ObjectRestResponse getReport(@PathVariable String reportId) throws Exception {
        Map<String, Object> resultMap = openvasTool.getReport(reportId);
        List<Map<String, Object>> results = (List<Map<String, Object>>) resultMap.get("results");
        List<String> resultIdList = new ArrayList<>();
        for (Map<String, Object> result : results) {
            String resultId = (String) result.get("resultId");
            resultIdList.add(resultId);
        }

        return new ObjectRestResponse(dwEnum.SUCCEESS.code(), "", resultIdList);
    }

    @ApiOperation("导出报告结果")
    @GetMapping("/exportReport")
    public BaseResponse exportReport(String reportId,String reportFormatId){
        try {
            openvasTool.exportReport(reportId,reportFormatId);
        } catch (Exception e) {
            e.printStackTrace();
            return new  BaseResponse(dwEnum.FAILURE.code(),"下载失败");
        }
        return new BaseResponse(dwEnum.SUCCEESS.code(),"下载成功");
    }

    @ApiOperation(value = "通过resultId获取结果", httpMethod = "GET")
    @GetMapping(value = "/getReportByReportId/{resultId}")
    public ObjectRestResponse getReportByReportId(@PathVariable String resultId) throws Exception {
        Map<String, Object> reportResult = openvasTool.getReportResult(resultId);
        return new ObjectRestResponse(dwEnum.SUCCEESS.code(), "", reportResult);
    }

    @ApiOperation(value = "通过任务id获取报告结果", httpMethod = "GET")
    @GetMapping(value = "/getReportByTaskID/{taskId}")
    public ObjectRestResponse getReportByTaskId(@PathVariable String taskId) throws Exception {
        List<Report> reportList = taskService.getReportByTaskId(taskId);
        return new ObjectRestResponse(dwEnum.SUCCEESS.code(), "", reportList);
    }


    @ApiOperation(value = "自动创建扫描任务", httpMethod = "POST")
    @PostMapping(value = "/createTaskAuto")
    public BaseResponse createTaskAuto(@RequestBody IpPort ipPort) throws Exception {
        TargetEntity target = new TargetEntity();
        target.setHosts(ipPort.getIp());
        target.setName(ipPort.getIp());
        target.setPortId("5f2029f6-56fe-11e1-bb94-406186ea4fc5");
        createTarget(target);
        List<TargetEntity> targetList = openvasTool.getTargetList();
        String targetId = null;
        for (TargetEntity targetEntity : targetList) {
            if (targetEntity.getName().equals(ipPort.getIp())) {
                targetId = targetEntity.getUuid();
            }
        }
        TaskEntity task = new TaskEntity();
        task.setTargetId(targetId);
        task.setName(ipPort.getIp());
        createTask(task);
        return new BaseResponse(dwEnum.SUCCEESS.code(), "新建任务成功");
    }


}
